"""
该文件提供了手势分割和质心提取的方法
This file provides some methods for gesture segmentation and centroid extraction.
"""
import numpy as np
import math
import ctypes


DLL_OPENCV = ctypes.CDLL('./Libs/opencv2413_mat.dll')   # 实现获取手势质心功能


# 获取手势的质心
def get_centroid(frame):
    frame_data = np.asarray(frame, dtype=np.uint8)
    frame_data = frame_data.ctypes.data_as(ctypes.c_char_p)     # mat转uchar*作为参数
    DLL_OPENCV.get_centroid.restype = ctypes.POINTER(ctypes.c_int)  # 从地址还原为int数组
    value = DLL_OPENCV.get_centroid(frame_data, frame.shape[0], frame.shape[1])     # 调用底层实现功能
    return value[0], value[1]


# 计算两点之间的距离
def get_distance(start, end):
    cx, cy = start
    lx, ly = end
    s = math.sqrt((cx - lx) * (cx - lx) + (cy - ly) * (cy - ly))
    return s


# 计算两点之间的方向角
def get_angle(start, end):
    dx = end[0] - start[0]
    dy = end[1] - start[1]
    if dy < 0:
        if dx > 0:
            angle = -math.atan(dy / dx)
        elif dx < 0:
            angle = math.pi / 2 + math.atan(dx / dy)
        else:
            angle = math.pi / 2
    elif dy > 0:
        if dx > 0:
            angle = 3 * math.pi / 2 + math.atan(dx / dy)
        elif dx < 0:
            angle = math.pi - math.atan(dy / dx)
        else:
            angle = 3 * math.pi / 2
    else:
        if dx > 0:
            angle = 0
        elif dx < 0:
            angle = math.pi
        else:
            angle = -1
    return angle
